<template>
  <div class="data-dashboard">
    <!-- 仪表盘头部 -->
    <div class="dashboard-header">
      <div class="header-left">
        <div class="logo-area">
          <!-- 使用logo.svg图片 -->
          <img src="@/assets/images/logo.svg" alt="天威线材" class="company-logo">
        </div>
      </div>
      <div class="header-title">
        <div class="title-text">天威线材换位生产车间可视化系统</div>
      </div>
      <div class="header-right">
        <!-- 全屏按钮 - 放在最左边 -->
        <el-button
          type="primary"
          circle
          class="fullscreen-icon-btn"
          @click="toggleFullScreen"
        >
          <el-icon><FullScreen /></el-icon>
        </el-button>

        <div class="time-display">
          <div class="date">{{ currentDate }}</div>
          <div class="time">{{ currentTime }}</div>
        </div>

        <div class="user-menu">
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" icon="UserFilled" />
              <span class="username">{{ currentUser?.username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>个人信息
                </el-dropdown-item>
                <el-dropdown-item command="changePassword">
                  <el-icon><Key /></el-icon>修改密码
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>

    <!-- 调试信息（只在开发模式下显示）-->
    <div v-if="false" class="debug-info">
      <h3>调试信息</h3>
      <p>设备列表: {{ equipmentList.length > 0 ? equipmentList : '无数据' }}</p>
      <p>图表初始化状态: {{ chartsInitialized ? '已初始化' : '未初始化' }}</p>
      <p>选中设备: {{ selectedEquipment || '无' }}</p>
      <button @click="toggleDebug">关闭调试信息</button>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="changePasswordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="changePasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitChangePassword" :loading="changing">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 仪表盘内容区 -->
    <div class="dashboard-content">
      <div class="dashboard-layout">
        <!-- 左侧图表区域 -->
        <div class="grid-layout">
          <!-- 第一行 -->
          <div class="chart-panel panel-large">
            <!-- 设备实时速度趋势图 -->
            <SpeedTrendChart
              :equipment-list="equipmentList"
              :initial-selected-equipment="selectedEquipment"
              @update:selected-equipment="selectedEquipment = $event"
            />
          </div>

          <div class="chart-panel panel-large">
            <!-- 班次产量对比图 -->
            <ShiftProductionChart />
          </div>

          <div class="chart-panel panel-large">
            <!-- 设备运行状态分布图 -->
            <DeviceStatusChart
              :equipment-list="equipmentList"
              :initial-selected-equipment="selectedStatusEquipment"
              @update:selected-equipment="selectedStatusEquipment = $event"
            />
          </div>

          <!-- 第二行 -->
          <div class="chart-panel panel-large">
            <!-- 报警时间设备排名 -->
            <AlarmRankingChart />
          </div>

          <div class="chart-panel panel-large">
            <!-- 操作员效率散点图 -->
            <OperatorEfficiencyChart />
          </div>

          <div class="chart-panel panel-large performance-ranking-panel">
            <!-- 业绩排行榜面板 -->
            <PerformanceRanking />
          </div>

          <!-- 第三行 -->
          <div class="chart-panel panel-wide" style="grid-column: 1 / span 3;">
            <!-- 实时产能统计图 -->
            <RealTimeProductionChart
              :equipment-list="equipmentList"
              :initial-selected-equipment="selectedProductionEquipment"
              :initial-time-window="productionWindow"
              @update:selected-equipment="selectedProductionEquipment = $event"
              @update:time-window="productionWindow = $event"
            />
          </div>
        </div>

        <!-- 右侧面板区域 -->
        <div class="right-panels-container">
          <!-- 设备状态面板 -->
          <DeviceStatusPanel />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, reactive } from 'vue'
import { User, Key, SwitchButton, ArrowDown, FullScreen } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import api from '@/services/api'
import '@/assets/styles/dashboard.css'

// 导入仪表盘组件
import SpeedTrendChart from '@/components/dashboard/SpeedTrendChart.vue'
import ShiftProductionChart from '@/components/dashboard/ShiftProductionChart.vue'
import DeviceStatusChart from '@/components/dashboard/DeviceStatusChart.vue'
import AlarmRankingChart from '@/components/dashboard/AlarmRankingChart.vue'
import OperatorEfficiencyChart from '@/components/dashboard/OperatorEfficiencyChart.vue'
import RealTimeProductionChart from '@/components/dashboard/RealTimeProductionChart.vue'
import DeviceStatusPanel from '@/components/dashboard/DeviceStatusPanel.vue'
import PerformanceRanking from '@/components/dashboard/PerformanceRanking.vue'

const router = useRouter()
const authStore = useAuthStore()

const currentUser = computed(() => authStore.user)

// 修改密码相关
const changePasswordDialogVisible = ref(false)
const changing = ref(false)
const passwordFormRef = ref(null)

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      ElMessage.info(`用户名: ${currentUser.value?.username}, 邮箱: ${currentUser.value?.email}`)
      break
    case 'changePassword':
      changePasswordDialogVisible.value = true
      break
    case 'logout':
      authStore.logout()
      router.push('/login')
      ElMessage.success('已成功退出登录')
      break
  }
}

// 提交修改密码
const submitChangePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()

    changing.value = true

    try {
      // 检查当前用户和令牌状态
      console.log('当前用户信息:', {
        id: authStore.user?.id,
        username: authStore.user?.username,
        roles: authStore.user?.roles
      })

      // 发送修改密码请求
      const response = await api.changePassword(passwordForm.currentPassword, passwordForm.newPassword)
      console.log('密码修改成功:', response.data)

      ElMessage.success('密码修改成功')
      changePasswordDialogVisible.value = false

      // 重置表单
      passwordForm.currentPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } catch (error) {
      console.error('密码修改失败:', error)

      // 显示错误消息
      const errorMessage = error.response?.data?.message || '密码修改失败，请检查当前密码是否正确'
      ElMessage.error(errorMessage)

      // 如果是当前密码错误
      if (error.response?.status === 401) {
        ElMessage.error('当前密码错误，请重新输入')
      }
      // 如果错误消息包含"认证失败"或"登录"，则重定向到登录页面
      else if (errorMessage.includes('认证失败') || errorMessage.includes('登录')) {
        console.log('检测到认证问题，将重定向到登录页面')
        setTimeout(() => {
          authStore.logout()
          router.push('/login')
        }, 1500)
      }
    } finally {
      changing.value = false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.warning('请正确填写密码信息')
  }
}

// 响应式数据
// 时间显示
const currentDate = ref('')
const currentTime = ref('')
const isFullscreen = ref(false)

// 更新时间显示
const updateTimeDisplay = () => {
  const now = new Date()
  currentDate.value = now.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'long' })
  currentTime.value = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

// 设备和图表相关数据
const equipmentList = ref([])
const selectedEquipment = ref('')
const selectedStatusEquipment = ref('')
const selectedProductionEquipment = ref('')
const productionWindow = ref(15)
const chartsInitialized = ref(false)
const showDebug = ref(false)

// 切换调试信息显示
const toggleDebug = () => {
  showDebug.value = !showDebug.value
}

// 切换全屏模式
const toggleFullScreen = () => {
  try {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen().then(() => {
        isFullscreen.value = true
      }).catch(err => {
        console.error('无法进入全屏模式:', err)
        ElMessage.error(`无法进入全屏模式: ${err.message}`)
      })
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen().then(() => {
          isFullscreen.value = false
        }).catch(err => {
          console.error('退出全屏出错:', err)
          ElMessage.error(`退出全屏出错: ${err.message}`)
        })
      }
    }
  } catch (error) {
    console.error('全屏操作出错:', error)
    ElMessage.error(`全屏操作出错: ${error.message}`)
  }
}

// 获取设备列表
const fetchEquipmentList = async () => {
  try {
    const response = await api.getEquipmentList()
    equipmentList.value = response.data.equipment || []
    console.log('获取到设备列表:', equipmentList.value)
  } catch (error) {
    console.error('获取设备列表失败:', error)
    // 使用模拟数据
    equipmentList.value = ['设备1', '设备2', '设备3', '设备4', '设备5']
  }
}

// 生命周期钩子
onMounted(async () => {
  console.log('DataDashboard组件已挂载')

  // 更新时间显示
  updateTimeDisplay()
  const timeInterval = setInterval(updateTimeDisplay, 1000)

  // 获取设备列表
  await fetchEquipmentList()

  // 初始化用户信息
  if (!currentUser.value) {
    authStore.user = {
      username: 'admin',
      email: 'admin@example.com'
    }
  }

  // 组件卸载时清除定时器
  onBeforeUnmount(() => {
    clearInterval(timeInterval)
  })
})
</script>

<style scoped>
.data-dashboard {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  background-color: #001529;
  color: white;
  overflow: hidden;
}

.dashboard-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background-color: rgba(0, 21, 41, 0.8);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo-area {
  display: flex;
  align-items: center;
}

.company-logo {
  height: 40px;
  margin-right: 15px;
}

.header-title {
  flex: 1;
  text-align: center;
}

.title-text {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  text-shadow: 0 0 10px rgba(24, 144, 255, 0.5);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
  z-index: 100;
}

.user-menu {
  z-index: 100;
}

.user-info {
  display: flex;
  align-items: center;
  background-color: rgba(0, 21, 41, 0.9);
  padding: 5px 15px;
  border-radius: 25px;
  cursor: pointer;
  color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
  border: 1px solid rgba(24, 144, 255, 0.5);
  transition: all 0.3s ease;
  min-width: 120px;
  height: fit-content;
}

.username {
  margin: 0 8px;
  font-size: 14px;
}

.time-display {
  text-align: right;
  min-width: 150px;
  z-index: 100;
}

.date {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.time {
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
}

.fullscreen-icon-btn {
  background-color: #1890ff !important;
  border-color: #1890ff !important;
  color: white !important;
  font-size: 16px;
  cursor: pointer;
  z-index: 1000 !important;
  box-shadow: 0 0 10px rgba(24, 144, 255, 0.5);
  margin-right: 15px;
  transition: all 0.3s;
  position: relative;
  height: 36px !important;
  width: 36px !important;
}

.fullscreen-icon-btn:hover {
  background-color: #40a9ff !important;
  border-color: #40a9ff !important;
}

.dashboard-content {
  flex: 1;
  overflow: hidden;
  padding: 15px;
}

.dashboard-layout {
  display: flex;
  height: 100%;
  gap: 15px;
}

.grid-layout {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: minmax(300px, auto);
  gap: 15px;
  overflow-y: auto;
  padding-right: 15px;
}

.panel-large {
  grid-row: span 1;
  grid-column: span 1;
  min-height: 300px;
}

.panel-medium {
  grid-row: span 1;
  grid-column: span 1;
  min-height: 300px;
}

.panel-wide {
  grid-column: span 3;
  min-height: 300px;
}

.performance-ranking-panel {
  grid-column: span 1;
  grid-row: span 1;
  background-color: rgba(0, 21, 41, 0.7);
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(30, 177, 252, 0.3);
  min-height: 300px;
}

.right-panels-container {
  width: 320px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.debug-info {
  position: fixed;
  top: 70px;
  right: 20px;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 10px;
  border-radius: 5px;
  z-index: 1000;
  max-width: 400px;
  max-height: 300px;
  overflow: auto;
}

/* 响应式布局 */
@media screen and (max-width: 1600px) {
  .grid-layout {
    grid-template-columns: repeat(2, 1fr);
  }

  .panel-wide {
    grid-column: span 2;
  }

  /* 屏幕变小时缩小设备状态面板 */
  .device-status-panel {
    width: 240px;
  }
}

@media screen and (max-width: 1200px) {
  .grid-layout {
    grid-template-columns: 1fr;
  }

  .panel-wide {
    grid-column: span 1;
  }
}

/* 用户菜单样式 */
.user-menu {
  display: flex;
  align-items: flex-start;
  height: fit-content;
  margin-top: -8px;
  margin-right: 160px;
}

.user-info {
  display: flex;
  align-items: center;
  background-color: rgba(0, 21, 41, 0.9);
  padding: 5px 15px;
  border-radius: 25px;
  cursor: pointer;
  color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
  border: 1px solid rgba(24, 144, 255, 0.5);
  transition: all 0.3s ease;
  min-width: 120px;
  height: fit-content;
}

.username {
  margin: 0 8px;
  font-size: 14px;
}
</style>
